<?php

namespace app\api\controller\v1;

use app\api\model\Address as AddressModel;
use app\api\model\Course as CourseModel;
use app\api\model\CourseOrder as CourseOrderModel;
use app\api\model\RemindOrder as RemindOrderModel;
use app\api\model\TeacherBusy as TeacherBusyModel;
use app\api\model\TeacherCourse as TeacherCourseModel;
use app\api\model\User as UserModel;
use app\api\model\UserMoneyLog as UserMoneyLogModel;
use app\api\service\CourseOrderService;
use app\common\service\AlibabaCloudService;
use app\common\service\EasyWechatService;
use app\api\validate\ConfirmOrderValidate;
use app\api\validate\SubmitOrderValidate;
use app\common\controller\BaseController;
use think\Db;
use app\api\model\Teacher as TeacherModel;

class Order extends BaseController
{
    protected $noNeedLogin = [''];
    /**
     * 确认订单页面
     */
    public function confirm(ConfirmOrderValidate $confirmOrderValidate)
    {
        $this->isPost();
        $data = $this->request->post();
        $this->paramValidate($confirmOrderValidate, $data);
        //课程
        $teacherCourse = TeacherCourseModel::getByTeacherCourseId($data['teacher_course_id'], false);
        if (!$teacherCourse->onlineswitch) {
            $this->errorMsg(10001);
        }
        //地址
        $userId = $this->userId;
        $address = AddressModel::getDefaultAddress($userId);
        //用户余额
        $user = UserModel::find($userId);
        if (!$user) {
            $this->errorMsg(9996);
        }
        $this->success('', [
            'teacher_course' => $teacherCourse,
            'classdata' => $data['classdata'],
            'address' => $address,
            'money' => $user->money
        ]);
    }

    /**
     * 立即支付
     */
    public function submit(SubmitOrderValidate $submitOrderValidate, CourseOrderService $courseOrderService, EasyWechatService $easyWechatService)
    {
        $this->isPost();
        $data = $this->request->post();
        $this->paramValidate($submitOrderValidate, $data);
        //是否已选上课时间
        if (isset($data['course']) && $data['course']) {
            //预约课次是否一致
            if (count($data['course']) != $data['num']) {
                $this->errorMsg(13000);
            }
            //预约时间是否忙碌
            TeacherBusyModel::isBuys($data['teacher_course_id'], $data['course']);
        }
        $data['user_id'] = $this->userId;
        //是否正常接单
        $teacherCourse = TeacherCourseModel::find($data['teacher_course_id']);
        if (!$teacherCourse || !$teacherCourse->onlineswitch) {
            $this->errorMsg(10001);
        }
        $user = UserModel::find($this->userId);
        if (!$user) {
            $this->errorMsg(9996);
        }
        //创建订单
        $courseOrder = $courseOrderService->create($data);
        if (!$courseOrder) {
            $this->forbidden();
        }

        switch ($data['pay_type']) {
            //账号余额
            case 1:
                if ($courseOrder->total_price > $user->money)
                {
                    $this->errorMsg(10003);
                }
                $this->paySuccess($courseOrder, $user, 1);
                break;
            case 2:
                $res = $easyWechatService->unify(
                    $courseOrder->order_no,
                    $courseOrder->total_price,
                    $user->wxapp_openid,
                    config('wechat.order_notify_url')
                );
                $res['course_order_id'] = $courseOrder->course_order_id;
                $this->success('', $res);
                break;
            default:
                $this->errorMsg(13004);
                break;
        }
    }

    /**
     * 订单支付
     */
    public function pay(EasyWechatService $easyWechatService)
    {
        $this->isPost();
        $courseOrderId = $this->notEmpty('course_order_id');
        $payType = $this->notEmpty('pay_type');
        $courseOrder = CourseOrderModel::find($courseOrderId);
        if (!$courseOrder) {
            $this->errorMsg(13001);
        }
        if ($courseOrder->status != 1) {
            $this->errorMsg(13003);
        }
        $user = UserModel::find($this->userId);
        if (!$user) {
            $this->errorMsg(9996);
        }
        //是否正常接单
        $teacherCourse = TeacherCourseModel::find($courseOrder->teacher_course_id);
        if (!$teacherCourse || !$teacherCourse->onlineswitch) {
            $this->errorMsg(10001);
        }
        switch ($payType) {
            //账号余额
            case 1:
                if ($courseOrder->total_price > $user->money)
                {
                    $this->errorMsg(10003);
                }
                $this->paySuccess($courseOrder, $user, 1);
                break;
            case 2:
                $res = $easyWechatService->unify(
                    $courseOrder->order_no,
                    $courseOrder->total_price,
                    $user->wxapp_openid,
                    config('wechat.order_notify_url')
                );
                $res['course_order_id'] = $courseOrder->course_order_id;
                $this->success('', $res);
                break;
            default:
                $this->errorMsg(13004);
                break;
        }
        $this->success('', $res);
    }

    /**
     * 主动回调
     */
    public function notify(EasyWechatService $easyWechatService)
    {
        $orderNo = $this->notEmpty('order_no');
        $courseOrder = CourseOrderModel::getByOrderNo($orderNo);
        if (!$courseOrder) {
            $this->errorMsg(13001);
        }
        $user = UserModel::find($courseOrder->user_id);
        if (!$user) {
            $this->errorMsg(9996);
        }
        if ($courseOrder->status == 2) {
            $this->success('', ['course_order_id' => $courseOrder->course_order_id]);
        }
        //查询支付订单
        $res = $easyWechatService->find($orderNo);
        $courseOrder->transaction_id = $res['transaction_id'];
        $this->paySuccess($courseOrder, $user, 2);
    }

    /**
     * 自动回调
     */
    public function paymentResult(EasyWechatService $easyWechatService)
    {
        $response = $easyWechatService->app()->handlePaidNotify(function ($res, $fail) {
            if ($res['return_code'] === 'SUCCESS' && $res['result_code'] === 'SUCCESS') {
                $courseOrder = CourseOrderModel::getByOrderNo($res['out_trade_no']);
                if ($courseOrder && $courseOrder->status == 1) {
                    $user = $user = UserModel::find($courseOrder->user_id);
                    if (!$user) {
                        return true;
                    }
                    $courseOrder->transaction_id = $res['transaction_id'];
                    $this->paySuccess($courseOrder, $user, 2);
                }
            } else {
                return $fail('支付异常，请联系管理员');
            }
        });
        $response->send();
    }


    /**
     * 支付处理
     */
    private function paySuccess($courseOrder, $user, $payment)
    {
        Db::startTrans();
        try {
            //更新订单
            $courseOrder->status = 2;
            $courseOrder->payment = $payment;
            $courseOrder->save();
            //用户
            if ($payment == 1) {
                UserMoneyLogModel::add($user, -$courseOrder->total_price, '预约课程');
                $user->money -= $courseOrder->total_price;
                $user->save();
            }
            //更新课表状态
            $course = CourseModel::getByOrderId($courseOrder->course_order_id);
            $courseStatus = $course && $course->date ? 3 : 2;
            CourseModel::updateByOrderId($courseOrder->course_order_id, ['status' => $courseStatus]);
            //订单提醒
            RemindOrderModel::add($courseOrder, 2);

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
        if (isset($e)) {
            $this->forbidden();
        }
        //发送订阅消息
        $this->subscribeData($courseOrder, $user);
        //发送老师短信消息
        $teacher = TeacherModel::find($courseOrder->teacher_id);
        if ($teacher) {
            AlibabaCloudService::sendSms($teacher->phone, 'SMS_200185396');
        }
        $this->success('', ['course_order_id' => $courseOrder->course_order_id]);

    }

    /**
     * 订阅数据
     */
    private function subscribeData($courseOrder, $user)
    {
        $data = [
            'template_id' => config('wechat.template')['order_success'],
            'touser' => $user->wxapp_openid,
            'page' => '',
            'data' => [
                'character_string6' => [
                    'value' => $courseOrder->order_no
                ],
                'amount10' => [
                    'value' => numberFormat($courseOrder->total_price)
                ],
                'thing9' => [
                    'value' => '您已下单成功，快去预约教师上课吧。'
                ]
            ]
        ];
        $easywechatService = new EasyWechatService();
        $easywechatService->send($data);
    }

}
